package com.usian.user.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.dtos.LoginDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.user.mapper.ApUserMapper;
import com.usian.user.service.ApUserLoginService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import com.usian.utils.common.AppJwtUtil;
import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserLoginServiceImpl implements ApUserLoginService {
    @Autowired
    ApUserMapper apUserMapper;

    @Override
    public ResponseResult login(LoginDto dto) {
        //参数校验
        if (dto.getEquipmentId() == null && (StringUtils.isEmpty(dto.getPhone()))
                && (StringUtils.isEmpty(dto.getPassword()))){
            return ResponseResult.errorResult(AppHttpCodeEnum.NULL_CANSHU);
        }
        //判断登录还是不登录
        if (!(StringUtils.isEmpty(dto.getPhone())) && !(StringUtils.isEmpty(dto.getPassword()))){
            //登录
            QueryWrapper<ApUser> apUserQueryWrapper = new QueryWrapper<>();
            apUserQueryWrapper.eq("phone",dto.getPhone());
//            ApUser apUser = apUserMapper.selectOne(apUserQueryWrapper);
            ApUser apUser = apUserMapper.findbyphone(dto.getPhone());
            if (apUser==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.NULL_CANSHU,"用户不存在");
            }
            String pwd = DigestUtils.md5DigestAsHex((dto.getPassword() + apUser.getSalt()).getBytes());
            if (apUser.getPassword().equals(pwd)){
                Map<String,Object> map=new HashMap<>();
                apUser.setPassword("");
                apUser.setSalt("");
                map.put("token",AppJwtUtil.getToken(apUser.getId().longValue()));
                map.put("user",apUser);
                return ResponseResult.okResult(map);
            }else {
                return ResponseResult.errorResult(AppHttpCodeEnum.NULL_CANSHU,"密码错误");
            }
        }else {
            //先不登录
            if (dto.getEquipmentId()==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.NULL_CANSHU,"设备id为空");
            }
            Map<String,Object> map = new HashMap<>();
            long A=0;
            map.put("token",AppJwtUtil.getToken(A));
            return ResponseResult.okResult(map);
        }
    }
}
